import cv2

# 创建级联器
faces = cv2.CascadeClassifier("/haarcascades/haarcascade_frontalface_default.xml")

cv2.namedWindow("video")
# 捕获视频文件
cap = cv2.VideoCapture("C:\\Users\\86191\\Videos\\face.mp4")
# 获取视频的宽度和高度
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# 创建视频写入器
fourcc = cv2.VideoWriter_fourcc(*'XVID')
vm = cv2.VideoWriter('C:\\Users\\86191\\Videos\\face.avi', fourcc, 20.0, (frame_width, frame_height))


while cap.isOpened():
    ret,frame = cap.read()
    frame = cv2.flip(frame, 1)
    if not ret:
        break
    # 灰度化
    gary = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 检测人脸
    face = faces.detectMultiScale(gary,1.3,5)
    for (x,y,w,h) in face:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
    cv2.imshow("video", frame)
    vm.write(frame)
    key = cv2.waitKey(1)
    if key == 27 & key == ord('q'):
        break


cap.release()
cv2.destroyAllWindows()

